package com.tjl.foodapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tjl.foodapp.utils.OkHttpClientUtil;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    public static SharedPreferences sp;

    EditText et_username,et_password;

    Button loginBtn,registerBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        loginBtn = findViewById(R.id.loginBtn);
        registerBtn = findViewById(R.id.registerBtn);
        //初始化sp
        sp = getSharedPreferences("user_info",MODE_PRIVATE);
        String username = sp.getString("username", "");
        //自动填写账号
        if (StringUtils.isNoneBlank(username)){
            et_username.setText(username);
        }

        loginBtn.setOnClickListener(v -> {
            String name = et_username.getText().toString();
            String pass = et_password.getText().toString();
            if (name.isEmpty() || pass.isEmpty()){
                Toast.makeText(LoginActivity.this, "请输入用户名或密码", Toast.LENGTH_SHORT).show();
                return;
            }
            new NetworkTask().execute();
        });
        registerBtn.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });

    }
    private class NetworkTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            try {
                String name = et_username.getText().toString();
                String pass = et_password.getText().toString();
                JSONObject reqJson = new JSONObject();
                reqJson.put("username", name);
                reqJson.put("userpass", pass);

                return OkHttpClientUtil.doPostJson(Utils.urlBase + "and_login.do", reqJson.toString());
            } catch (Exception e) {
                Log.e("NetworkTask", "Error fetching data", e);
                e.printStackTrace();
                return e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int userId = jsonObject.getInt("user_id");
                    if ("登陆成功".equals(jsonObject.getString("msg"))
                        || userId > 0){
                        //保存账号
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("username", et_username.getText().toString());
                        edit.apply();

                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("user_id", userId);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }else{
                        Toast.makeText(LoginActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(LoginActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                System.out.println("请求失败");
                Toast.makeText(LoginActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}